package com.xjgc.rest.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.DateUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * crm系统接口配置
 *
 * @author: 小逗号
 * @date: 2023/8/11
 * @description:
 * @since:
 */
@Slf4j
@Setter
@Configuration
@ConfigurationProperties(prefix = "msi.config.fss")
public class FssConfig {
    @Resource
    private RestTemplate restTemplate;

    private String appId;
    private String appSecret;
    private String language;
    private String tenantid;
    private String accountId;
    private String user;
    private String userType;

    /**
     * 获取app_token**
     */
    private String appTokenUrl;
    /**
     * 获取access_token**
     */
    private String accessTokenUrl;

    private final Token token = new Token();


    class Token {
        private String appToken;
        private String accessToken;
        private Long expireTime;
    }

    public String getToken() {
        if (token.expireTime == null) {
            reGetToken();
        } else {
            int diff = DateUtils.dateDiff('m', DateUtils.getCalendar(), DateUtils.getCalendar(token.expireTime));
            //token有效期小于30分钟,重新获取token
            if (diff < 30) {
                reGetToken();
            }
        }

        return token.accessToken;
    }

    private void reGetToken() {
        log.info("调用FSS系统-获取app_token接口:{}", appTokenUrl);
        Map<String, String> param1 = getParam1();
        log.info("param:{}", param1);
        /*fss系统微服务返回的是json字符串 string */
        String response = restTemplate.postForObject(appTokenUrl, param1, String.class);
        log.info("FSS系统-获取app_token响应:{}", response);
        Result result = parseResponse(response);
        if (!result.isSuccess()) {
            throw new JeecgBootException(result.getMessage());
        }
        JSONObject data = (JSONObject) result.getResult();
        String app_token = data.getString("app_token");

        log.info("调用FSS系统-获取access_token接口:{}", accessTokenUrl);
        Map<String, String> param2 = getParam2(app_token);
        log.info("param:{}", param2);
        /*fss系统微服务返回的是json字符串 string */
        response = restTemplate.postForObject(accessTokenUrl, param2, String.class);
        log.info("FSS系统-获取access_token响应:{}", response);
        result = parseResponse(response);
        if (!result.isSuccess()) {
            throw new JeecgBootException(result.getMessage());
        }
        data = (JSONObject) result.getResult();

        String access_token = data.getString("access_token");
        /*expire_time -> {Long@871} 1699875851159*/
        Long expire_time = data.getLong("expire_time");
        token.expireTime = expire_time;
        token.accessToken = access_token;
        token.appToken = app_token;
    }

    private Result parseResponse(String response) {
        JSONObject res = JSON.parseObject(response);

        /*status -> {Boolean@856} true*/
        Boolean status = res.getBoolean("status");

        if (!status) {
            /*state -> success*/
            //String state = res.getString("state");
            log.error(res.toJSONString());
            return Result.error("财务共享系统身份认证失败!");
        }

        /*data -> {JSONObject@852}  size = 5*/
        JSONObject data = res.getJSONObject("data");
        /*success -> {Boolean@856} true */
        Boolean success = data.getBoolean("success");
        if (!success) {
            /*error_code -> 0*/
            Integer error_code = data.getInteger("error_code");
            /*error_desc -> */
            String error_desc = data.getString("error_desc");
            log.error(res.toJSONString());
            return Result.error("财务共享系统身份认证失败!");
        }
        /*app_token -> ebe7778d-7bb5-4ba9-a38e-b32f79fc83db*/
        //String app_token = data.getString("app_token");
        /*expire_time -> {Long@871} 1699875851159*/
        //Long expire_time = data.getLong("expire_time");

        return Result.OK(data);
    }


    private static Map<String, String> param1;

    private Map<String, String> getParam1() {
        if (param1 == null) {
            param1 = new HashMap<>(4);
            param1.put("appId", this.appId);
            param1.put("appSecret", this.appSecret);
            param1.put("language", this.language);
        }
        return param1;
    }

    private static Map<String, String> param2;

    private Map<String, String> getParam2(String appToken) {
        if (param2 == null) {
            param2 = new HashMap<>(6);
            param2.put("user", this.user);
            param2.put("usertype", this.userType);
            param2.put("tenantid", this.tenantid);
            param2.put("accountId", this.accountId);
        }
        param2.put("apptoken", appToken);
        return param2;
    }


}
